// 模板、客户端交互功能未启用

const express = require('express')
const fs = require('fs')
const {createBundleRenderer} = require('vue-server-renderer')
const setUpDevServer = require('./build/setUpDevServer')

const isProd = process.env.NODE_MODE === 'production'
const server = express()

let renderer = null
let onReady = null

if (isProd) {
    const serverBundle = require('./dist/vue-ssr-server-bundle.json')
    const clientManifest = require('./dist/vue-ssr-client-manifest.json')
    const template = fs.readFileSync('./index.template.html', 'utf-8')
    renderer = createBundleRenderer(serverBundle, {
        template,
        clientManifest
    })
} else {
    // 监视文件变化，重新生成渲染器
    onReady = setUpDevServer(server,(serverBundle,clientManifest,template)=>{
        renderer = createBundleRenderer(serverBundle, {
            template,
            clientManifest
        })
   })
}

// 前缀、具体路径
server.use('/dist', express.static('./dist'))
const render = async (req, res) => {
    try {
        const html = await renderer.renderToString({
            title: 'title',
            meta: '<meta name="description" content="测试" />',
            url: req.url
        })
        res.setHeader('Content-Type','text/html; charset=utf8')
        res.end(html)
    } catch (error) {
        console.log(error)
        res.status(500).end('Internal Server Error.')
    }
}

// 所有的路由
server.get('*', isProd ? render : async (req, res) => {
    if(req.url.endsWith('favicon.ico')){
        res.end('')
        return
    }
    // 等待 renderer 然后渲染
    await onReady
    render(req, res)
})
server.listen(3000, () => {
    console.log(`server running at 3000`)
})
